package com.onepower.core.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.onepower.core.domain.mapper.SysRoleInfoMapper;
import com.onepower.core.domain.request.SysRoleForm;
import com.onepower.core.domain.response.SysRoleInfo;
import com.onepower.core.modules.repository.entity.SysRole;
import com.onepower.core.modules.repository.entity.SysRoleMenu;
import com.onepower.core.modules.repository.mapper.SysRoleMapper;
import com.onepower.core.modules.service.ISysRoleMenuService;
import com.onepower.core.modules.service.ISysRoleService;
import com.onepower.core.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色信息表 服务实现类
 * </p>
 *
 * @author kin
 * @since 2018-08-01
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    private ISysRoleMenuService sysRoleMenuService;

    @Autowired
    HttpServletRequest request;


    @Transactional
    @Override
    public void save(SysRoleForm sysRoleForm) {
        if (sysRoleForm.getId() == null) {
            sysRoleForm.setCreateUserId(SecurityUtils.getCurrentUserId(request));
            baseMapper.insert(sysRoleForm);
        } else {
            sysRoleForm.setUpdateUserId(SecurityUtils.getCurrentUserId(request));
            baseMapper.updateById(sysRoleForm);
            sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id", sysRoleForm.getId()));
        }
        sysRoleMenuService.saveBatch(roleMenuList(sysRoleForm));
    }

    @Override
    public SysRoleInfo getRoleInfo(Integer roleId) {
        SysRole role = this.getById(roleId);
        //查询角色对应的菜单
        List<Integer> menuIdList = sysRoleMenuService.getMenuIdList(roleId);
        SysRoleInfo sysRoleInfo = SysRoleInfoMapper.MAPPER.converter(role);
        sysRoleInfo.setMenuIdList(menuIdList);

        return sysRoleInfo;
    }

    private List<SysRoleMenu> roleMenuList(SysRoleForm roleInfo) {
        List<SysRoleMenu> roleMenuList = new ArrayList<>();
        roleInfo.getMenuIdList().forEach(x -> {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setMenuId(x);
            sysRoleMenu.setRoleId(roleInfo.getId());
            roleMenuList.add(sysRoleMenu);
        });

        return roleMenuList;
    }
}
